package edu.mama.college.service;

import edu.mama.college.mapper.SmsSendRecordMapper;
import edu.mama.college.mapper.UserMapper;
import edu.mama.college.model.Page;
import edu.mama.college.model.SmsSendRecord;
import edu.mama.college.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SmsSendRecordMapper smsSendRecordMapper;

    public User findByMobileAndPassword(String mobile, String password) {
        return userMapper.findByMobileAndPassword(mobile, password);
    }

    public User findByMobile(String mobile){
        return userMapper.findByMobile(mobile);
    }


    public void register(User user) {
        userMapper.register(user);
    }

    public void updateLastLoginTime(User user){
        userMapper.updateLastLoginTime(user);
    }

    public int updateNickname(User user){
        return userMapper.updateNickname(user);
    }

    public void updatePassword(User user){
        userMapper.updatePassword(user);
    }


    public void updateAvatar(User user){
        userMapper.updateAvatar(user);
    }

    public Page<User> userList(int page, int size, String mobile, String begin, String end){
        int total = userMapper.countTotal(mobile,begin,end);
        List<User> userList =  userMapper.userList(page,size,mobile,begin,end);
        return new Page<>(page, size,total,userList);
    }


    /**
     * 发送验证码
     * @param mobile
     * @param code
     */
    public void sendSms(String mobile,String code){
        try{
            smsSendRecordMapper.insert(mobile,code);
        }catch(DuplicateKeyException e){
            smsSendRecordMapper.update(mobile,code);
        }
    }

    /**
     * 获取验证码
     * @param length
     * @return
     */
    public String getSmsCode(int length){
        double value = Math.random() * Math.pow(10,length);

        int intValue = (int) value;

        return String.format("%0" + length + "d",intValue);
    }

    /**
     * 修改手机号
     */
    public int changeMobile(String mobile,int userId){
       return userMapper.changeMobile(userId,mobile);
    }
}
